package com.example.controller;

import com.example.entity.RestBean;
import com.example.service.ImageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {

    @Resource
    ImageService imageService;

    @PostMapping("/avatar")
    public RestBean<String> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestAttribute("id") int id) throws Exception {

//        if (file.getSize() > 1024 * 100) {
//            return RestBean.failure(400, "文件大小不能超过100KB");
//        }
        log.info("用户{}上传了头像{}", id, file.getOriginalFilename());
        String url = imageService.uploadAvatar(file, id);
        if (url != null) {
            log.info("用户{}上传头像成功，大小:{}", id, file.getSize());
            return RestBean.success(url);
        } else {
            log.error("用户{}上传头像失败", id);
            return RestBean.failure(500, "上传失败");
        }
    }

    @PostMapping("/cache")
    public RestBean<String> uploadImage(@RequestParam("file") MultipartFile file, @RequestAttribute("id") int id) throws Exception {

//        if (file.getSize() > 1024 * 100) {
//            return RestBean.failure(400, "文件大小不能超过100KB");
//        }
        log.info("用户{}上传了图片{}", id, file.getOriginalFilename());
        String url = imageService.uploadImage(file, id);
        if (url != null) {
            log.info("用户{}上传图片成功，大小:{}", id, file.getSize());
            return RestBean.success(url);
        } else {
            log.error("用户{}上传图片失败", id);
            return RestBean.failure(500, "上传失败");
        }
    }

}
